import pygame
import modGame

class MyGame:
    def __init__(self):
        pygame.init()
        pygame.display.set_caption("飞机坦克")
        self._screen = pygame.display.set_mode((800, 600))
        self._timer = pygame.time.Clock()
        self._margin = 8

        # 一架飞机
        self._jet = modGame.Jet()
        # 飞机发射的子弹
        self._max_bullets = 3 # 最多只允许同时出现3颗子弹
        self._bullets = []
        # 五辆坦克
        self._tanks = []
        for i in range(5):
            self._tanks.append(modGame.Tank())
    
    def play(self):
        self._set_jets_pos()
        self._set_tanks_pos()

        keep_going = True
        while keep_going:
            for event in pygame.event.get():
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_SPACE:
                        if len(self._bullets) < self._max_bullets:
                            bullet = self._jet.OpenFire() # 开火
                            self._bullets.append(bullet)
                elif event.type == pygame.QUIT:
                    keep_going = False
            
            self._screen.fill((0, 0, 0))
            # 坦克
            for tank in self._tanks:
                tank.render(self._screen)
            # 飞机
            self._jet.render(self._screen)
            # 子弹
            for bullet in self._bullets:
                bullet.render(self._screen)
            
            # 让子弹飞
            self._let_bullets_fly()

            pygame.display.update()
            self._timer.tick(60)

        pygame.quit()
    
    def _set_jets_pos(self):
        jetW = self._jet.width
        jetL = self._jet.length
        # 飞机居中
        jetX = (self._screen.get_width() - jetW) / 2 # 水平居中
        jetY = self._screen.get_height() - self._margin - jetL # 垂直靠底部
        self._jet.SetPositon(jetX, jetY) # 设定飞机的初始位置
    
    def _set_tanks_pos(self):
        tankW = self._tanks[0].width
        tankL = self._tanks[0].length
        # 五辆坦克分散
        tankX = (self._screen.get_width() - tankW) / 2 # 水平居中
        tankY = self._margin # 垂直靠顶部
        tankSpace = (self._screen.get_width() - self._margin*2 - tankW*len(self._tanks)) / 4
        for i in range(len(self._tanks)):
            self._tanks[i].SetPositon((tankW+tankSpace)*i+self._margin, tankY)
    
    def _let_bullets_fly(self):
        # 子弹飞行,如果飞出边界,清除子弹
        i = 0
        while i < len(self._bullets):
            posYNew = self._bullets[i].Fly()
            if posYNew < 0:
                del self._bullets[i]
            else:
                i += 1


myGame = MyGame()
myGame.play()